'use client';

import { useState, useEffect } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar } from 'recharts';
import { apiClient } from '@/lib/api';
import type { XLayerToken, XLayerPriceData } from '@/types/xlayer';

interface XLayerTradingChartProps {
  token: XLayerToken;
}

export function XLayerTradingChart({ token }: XLayerTradingChartProps) {
  const [chartData, setChartData] = useState<XLayerPriceData[]>([]);
  const [chartType, setChartType] = useState<'price' | 'volume'>('price');
  const [timeframe, setTimeframe] = useState<'1h' | '24h' | '7d' | '30d'>('24h');
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    loadChartData();
  }, [token.id, timeframe]);

  const loadChartData = async () => {
    setIsLoading(true);
    try {
      const data = await apiClient.getXLayerTokenChart(token.id, timeframe);
      setChartData(data.prices || generateMockData());
    } catch (error) {
      console.error('Failed to load chart data:', error);
      setChartData(generateMockData());
    } finally {
      setIsLoading(false);
    }
  };

  const generateMockData = (): XLayerPriceData[] => {
    const now = Date.now();
    const data: XLayerPriceData[] = [];
    const points = timeframe === '1h' ? 60 : timeframe === '24h' ? 24 : timeframe === '7d' ? 7 : 30;
    const interval = timeframe === '1h' ? 60000 : timeframe === '24h' ? 3600000 : 24 * 3600000;
    
    const basePrice = parseFloat(token.tokenPrice || '0.0001');
    let currentPrice = basePrice;
    
    for (let i = points; i >= 0; i--) {
      const timestamp = now - (i * interval);
      
      // Simulate price movement
      const change = (Math.random() - 0.5) * 0.1; // ±5% change
      currentPrice = Math.max(basePrice * 0.5, currentPrice * (1 + change));
      
      const volume = Math.random() * 10; // Random volume
      
      data.push({
        timestamp,
        price: currentPrice,
        volume
      });
    }
    
    return data;
  };

  const formatTimestamp = (timestamp: number) => {
    const date = new Date(timestamp);
    switch (timeframe) {
      case '1h':
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      case '24h':
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      case '7d':
        return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
      case '30d':
        return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
      default:
        return date.toLocaleString('zh-CN');
    }
  };

  const formatPrice = (price: number) => {
    if (price < 0.001) {
      return price.toExponential(2);
    }
    return price.toFixed(6);
  };

  const formatVolume = (volume: number) => {
    return volume.toFixed(2);
  };

  const getCurrentPrice = (): number => {
    if (chartData.length === 0) return 0;
    return chartData[chartData.length - 1].price;
  };

  const getPriceChange = () => {
    if (chartData.length < 2) return { change: 0, percentage: 0 };
    
    const current = chartData[chartData.length - 1].price;
    const previous = chartData[0].price;
    const change = current - previous;
    const percentage = (change / previous) * 100;
    
    return { change, percentage };
  };

  const { change, percentage } = getPriceChange();
  const isPositive = change >= 0;

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading chart data...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Chart Controls */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h3 className="text-lg font-semibold mb-2">{token.name} Trading Chart</h3>
          <div className="flex items-center space-x-4">
            <div>
              <span className="text-2xl font-bold">
                {formatPrice(getCurrentPrice())} ETH
              </span>
              <span className={`ml-2 text-sm ${isPositive ? 'text-green-600' : 'text-red-600'}`}>
                {isPositive ? '+' : ''}{formatPrice(change)} ({percentage.toFixed(2)}%)
              </span>
            </div>
          </div>
        </div>
        
        <div className="flex space-x-2">
          {/* Chart Type Selector */}
          <div className="flex bg-gray-100 rounded-lg p-1">
            <button
              onClick={() => setChartType('price')}
              className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${
                chartType === 'price'
                  ? 'bg-white text-orange-600 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              价格
            </button>
            <button
              onClick={() => setChartType('volume')}
              className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${
                chartType === 'volume'
                  ? 'bg-white text-orange-600 shadow-sm'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              成交量
            </button>
          </div>
          
          {/* Timeframe Selector */}
          <div className="flex bg-gray-100 rounded-lg p-1">
            {['1h', '24h', '7d', '30d'].map((tf) => (
              <button
                key={tf}
                onClick={() => setTimeframe(tf as typeof timeframe)}
                className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${
                  timeframe === tf
                    ? 'bg-white text-orange-600 shadow-sm'
                    : 'text-gray-600 hover:text-gray-900'
                }`}
              >
                {tf}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Chart */}
      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <ResponsiveContainer width="100%" height={400}>
          {chartType === 'price' ? (
            <LineChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis
                dataKey="timestamp"
                tickFormatter={formatTimestamp}
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#6b7280', fontSize: 12 }}
              />
              <YAxis
                tickFormatter={formatPrice}
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#6b7280', fontSize: 12 }}
                domain={['dataMin * 0.95', 'dataMax * 1.05']}
              />
              <Tooltip
                labelFormatter={(value) => formatTimestamp(value as number)}
                formatter={(value: number) => [formatPrice(value) + ' ETH', 'Price']}
                contentStyle={{
                  backgroundColor: '#fff',
                  border: '1px solid #e5e7eb',
                  borderRadius: '8px',
                  boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
                }}
              />
              <Line
                type="monotone"
                dataKey="price"
                stroke={isPositive ? '#10b981' : '#ef4444'}
                strokeWidth={2}
                dot={false}
                activeDot={{ r: 4, stroke: isPositive ? '#10b981' : '#ef4444', strokeWidth: 2 }}
              />
            </LineChart>
          ) : (
            <BarChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis
                dataKey="timestamp"
                tickFormatter={formatTimestamp}
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#6b7280', fontSize: 12 }}
              />
              <YAxis
                tickFormatter={formatVolume}
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#6b7280', fontSize: 12 }}
              />
              <Tooltip
                labelFormatter={(value) => formatTimestamp(value as number)}
                formatter={(value: number) => [formatVolume(value) + ' ETH', 'Volume']}
                contentStyle={{
                  backgroundColor: '#fff',
                  border: '1px solid #e5e7eb',
                  borderRadius: '8px',
                  boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
                }}
              />
              <Bar dataKey="volume" fill="#f97316" radius={[2, 2, 0, 0]} />
            </BarChart>
          )}
        </ResponsiveContainer>
      </div>

      {/* Chart Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-gray-50 rounded-lg p-4">
          <div className="text-sm text-gray-600 mb-1">Current Price</div>
          <div className="text-lg font-semibold">{formatPrice(getCurrentPrice())} ETH</div>
        </div>
        
        <div className="bg-gray-50 rounded-lg p-4">
          <div className="text-sm text-gray-600 mb-1">Price Change</div>
          <div className={`text-lg font-semibold ${isPositive ? 'text-green-600' : 'text-red-600'}`}>
            {isPositive ? '+' : ''}{percentage.toFixed(2)}%
          </div>
        </div>
        
        <div className="bg-gray-50 rounded-lg p-4">
          <div className="text-sm text-gray-600 mb-1">24h Highest</div>
          <div className="text-lg font-semibold">
            {formatPrice(Math.max(...chartData.map(d => d.price)))} ETH
          </div>
        </div>
        
        <div className="bg-gray-50 rounded-lg p-4">
          <div className="text-sm text-gray-600 mb-1">24h Lowest</div>
          <div className="text-lg font-semibold">
            {formatPrice(Math.min(...chartData.map(d => d.price)))} ETH
          </div>
        </div>
      </div>

      {/* Chart Info */}
      <div className="text-sm text-gray-500 text-center">
        <p>数据更新于 {new Date().toLocaleTimeString('zh-CN')}</p>
        <p className="mt-1">
          {token.launched 
            ? 'Token launched, price data from DEX' 
            : 'Presale stage, showing fixed price and simulated data'
          }
        </p>
      </div>
    </div>
  );
}